<template>
  <div class="container">
    <DataList
      ref="dataList"
      :propAutoFetchData="false"
      :propNoCheck="true"
      :propSearchFields="['code']"
      :propSearchTextAppend="'开票单号'"
      propUrl="/settlement/invoices/pageCommon"
      showFieldPk="id"
      :showFieldList="cpShowFieldList"
      :showDataFmtFun="showDataFmtFun"
      :vanFieldLabelWith5="true"
      @click="itemClick"
      @afterLoad="afterLoad"
      :sortDefault="{field: 'gmtCreate',type: 'desc'}"
    >
    </DataList>

    <!--品类选择-->
    <customDrawer  title="订单详情" ref="customDrawerOrder" :autoHide="false" p94Only placement="right" :footer="null">
      <template #content>
        <customSpace fullWidth style="top: 33px;padding: 5px 0px; position: fixed; top: 33px;  z-index: 999;
    background: #fff;"  v-if="!isReadonly && form.status == 0">
          <template #content>
            <customButton  title="审核通过" theme="success" size="medium" @click="pass" />
<!--            <customButton  title="打印" theme="success" size="medium" @click="printForm" v-if="form.status == 1"/>-->
          </template>
        </customSpace>

        <customForm :data="form"   ref="editForm" :disabled="isReadonly || form.status != 0" layoutMini
                    :rules="{invoiceNo: [{ required: true, message: '请输入', trigger: 'blur' }]}"
                    scrollToFirstError=""
        >
          <template #content>
            <div id="box-base" class="box-title" >开票信息</div>
            <customFormItem
              v-for="item in cpFormFieldList"  :key="item.name"
              :parent="_self" :form="form"
              :label="item.label" :name="item.name"  :type="item.queryType"
              :config="item.queryConfig"
              :full-width="24 == item.span"
              :disabled="!item.formItemEnabled"
              :scanBtn="item.scanBtn"
            />
            <customFormItem
              label="发票附件"
              name="fileInfo"
              :parent="_self"
              :form="form"
              :type="constCommon.formItemType.slot.name"
              fullWidth
            >
              <template #content>
                <customUpload
                  :data="{ fileRefId: form.id, fileRefTable: 'invoice', fileSavePath: 'invoice'}"
                  :hide="!form.id"
                  :max="20"
                  :disabled="isReadonly || form.status != 0"
                  multiple
                  theme="file"
                />
              </template>
            </customFormItem>
          </template>
        </customForm>

        <div id="box-dtl" class="box-title">开票明细</div>
        <DataList
          ref="dataListDtl"
          :propAutoFetchData="false"
          :propNoCheck="true"
          :propSearchFields="['materialName','materialSpec']"
          :propSearchTextAppend="'品名、品规'"
          propUrl="/settlement/bill_items/pageCommon"
          showFieldPk="id"
          :showFieldList="cpDtlshowFieldList"
          :vanFieldLabelWith5="true"
          :sortDefault="{field: 'gmtCreate',type: 'desc'}"
        >
        </DataList>
      </template>
    </customDrawer>
  </div>
</template>

<script>
import customUpload from '@/components/custom/form/customUpload.vue'
import utilPrint from '@/util/utilPrint.js'

export default {
  help: '结算管理-待审核发票',
  props: ['statusEq', 'readonly'],
  data() {
    return {
      poCode: '',
      activeNames: ['1'],
      form: {},
      submitPopShow: false,
    }
  },
  components: { customUpload},

  computed: {
    isReadonly() {
      return true == this.readonly
    },

    // 表单字段
    cpFormFieldList() {
      return this.cpShowFieldList.filter(item1 => !item1.showFormOpenDisabled)
    },

    // 主单据显示字段
    cpShowFieldList() {
      let fieldList = [
        { label: '开票单号', name: 'code', span: 24, isTitle: true },
        {
          label: '状态',
          name: 'status',
          span: 12,
          isTitleSub: true,
          queryType: this.constCommon.formItemType.selectDict.name,
          queryConfig: {
            dictType: this.constCommon.dictType.settlementInvoiceStatus,
            multiple: true
          },
        },
        {
          label: '开票金额',
          name: 'totalAmount',
          span: 12,
          filterDisabled: true,
          sortDisabled: true
        },
        {
          label: '发票号',
          name: 'invoiceNo',
          span: 24,
          filterDisabled: true,
          sortDisabled: true,
          formItemEnabled: true,
          scanBtn: true,
        },
        {
          label: '审核人',
          name: 'auditorName',
          span: 12,
          showFormDtlDisabled: true,
          filterDisabled: true,
          sortDisabled: true
        },
        {
          label: '审核时间',
          name: 'gmtAudited',
          span: 24,
          queryType: this.constCommon.formItemType.datePickerBetween.name,
          queryConfig: {
            format: this.dates.defaultDateTimePattern
          }, showFormDtlDisabled: true

        },
        {
          label: '创建时间',
          name: 'gmtCreate',
          span: 24,
          queryType: this.constCommon.formItemType.datePickerBetween.name,
          queryConfig: {
            format: this.dates.defaultDateTimePattern
          }
        },
        {
          label: '备注',
          name: 'remark',
          span: 24,
          filterDisabled: true,
          sortDisabled: true,
          showFormDtlDisabled: true,
          formItemEnabled: true
        }
      ]
      fieldList = [...fieldList, ...this.constCommon.filterCommon.spAndHp()]
      return fieldList
    },

    // 明细字段
    cpDtlshowFieldList() {
      let fieldList = [
        { label: '品名', name: 'materialName', span: 12, isTitle: true },
        { label: '品规', name: 'materialSpec', span: 24 },
        { label: '数量', name: 'qty', span: 12, filterDisabled: true, sortDisabled: true },
        { label: '单位', name: 'unit', span: 12, filterDisabled: true, sortDisabled: true },
        { label: '单价', name: 'price', span: 12, filterDisabled: true, sortDisabled: true },
        { label: '生产厂商', name: 'manufacturerName', span: 24 },
        { label: '批次', name: 'lot', span: 24 },
        { label: '注册证号', name: 'certificateNo', span: 24 },
        { label: '备注', name: 'remark', span: 24, sortDisabled: true },
        {
          label: '创建时间',
          name: 'gmtCreate',
          span: 24,
          queryType: this.constCommon.formItemType.datePicker.name,
          filterDisabled: true,
        },
      ]
      return fieldList
    }
  },
  mounted() {
    this.loadOrder()
  },
  methods: {
    loadOrder() {
      let wrapper = this.$newWrapper()
      if (this.statusEq) {
        wrapper.eq('status', this.statusEq)
      }
      this.$refs.dataList.setQueryWrapper(wrapper)
    },
    showDataFmtFun(data) {
      data.forEach(item => {
      })
      return data
    },
    itemClick(item) {
      Object.keys(item).forEach(key => {
        this.$set(this.form, key,item[key])
      })

      let wrapper = this.$newWrapper()
      wrapper.eq('invoiceId', this.form.id)
      this.$refs.dataListDtl.setQueryWrapper(wrapper)
      this.$refs.customDrawerOrder.show()
    },

    // 订单操作
    handleOrder(fun, title) {
      this.utilMessage.confirm(`是否${title}`, () => {
        this[fun]()
      })
    },

    // 审核通过
    pass() {
      this.$refs.editForm.validate().then((result) => {
        if (result && result == true) {
          this.utilMessage.confirm(`确认审核通过`, () => {
            this.passDo()
          })
        }
      })
    },

    // 打印
    printForm() {
      utilPrint.openPdfView(`打印开票单-${this.form.code}`, `/settlement/invoices/${this.form.id}/pdf-preview`)
    },

    // 审核通过
    passDo() {
      this.utilVue.loadShow(true)
      this.$ajax.post(`settlement/invoices/audit`, this.form).then((response) => {
        this.utilVue.loadHide()
        if (response.code == 0) {
          this.$refs.customDrawerOrder.hide()
          this.utilMessage.success(response.msg)
          this.loadOrder()
        }
      })
    },

    // 订单数据加载完
    afterLoad(data) {
      if (this.poCode) {
        if (!data || data.length == 0) {
          this.utilMessage.warning(`未找到符合条件的采购订单[${this.poCode}]`)
          return
        }
        if (data[0].code != this.poCode) {
          return
        }
        this.poCode = ''
        this.itemClick(data[0])
      }
    },
  },
  watch: {
    '$route.meta.poCode': {
      immediate: true,
      handler(newVal) {
        if (!newVal) {
          return
        }

        this.$nextTick(() => {
          this.poCode = newVal
          delete this.$route.meta.poCode
          const wrapper = this.$newWrapper().eq('code', this.poCode)
          this.$refs.dataList.setQueryWrapper(wrapper)
        })
      }
    }
  }
}
</script>
